package com.zhipu.balance.ui.vm.home.calculate.rapeseed

import android.annotation.SuppressLint
import android.text.TextUtils
import androidx.databinding.ObservableField
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.constant.TimeConstants
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.zhipu.balance.common.Constants
import com.zhipu.balance.listener.ChooseClickCallback
import com.zhipu.balance.listener.SerialPortListener
import com.zhipu.balance.mobile.dao.NumberDao
import com.zhipu.balance.mobile.dao.RecordRapeseedDao
import com.zhipu.balance.mobile.dao.RecordSoybeanDao
import com.zhipu.balance.mobile.event.RecordDaMi
import com.zhipu.balance.mobile.event.RecordRapeseed
import com.zhipu.balance.mobile.event.RecordRice
import com.zhipu.balance.pop.ConfirmPopup
import com.zhipu.balance.remotedata.systemapi.SystemApiService
import com.zhipu.balance.ui.home.calculate.dami.DaMiActivity
import com.zhipu.balance.ui.home.calculate.rapeseed.*
import com.zhipu.balance.ui.home.calculate.rapeseed.adapter.RapeseedAdapter
import com.zhipu.balance.ui.home.calculate.rice.*
import com.zhipu.balance.ui.home.calculate.rice.adapter.RiceAdapter
import com.zhipu.balance.ui.vm.BaseViewModel
import com.zhipu.balance.utils.InitializeUtils
import com.zhipu.balance.utils.OpenSerialPort
import com.zhipu.balance.utils.data.DisposeUtils
import com.zhipu.balance.utils.print.dami.DaMiPrintUtils
import com.zhipu.balance.utils.print.rapeseed.RapeseedPrintUtils
import com.zhipu.balance.utils.print.rice.RicePrintUtils
import com.zhipu.balance.utils.upload.rapeseed.RapeseedUploadUtils
import com.zhipu.balance.utils.upload.rice.RiceUploadUtils
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

/**
 * 功能计算-油菜籽
 */
class RapeseedViewModel(mSystemApiService : SystemApiService) : BaseViewModel(mSystemApiService), SerialPortListener,ChooseClickCallback {
    /**
     * 显示
     */
    var display = ObservableField(true)


    /**
     * 称重重量
     */
    var weighing = ObservableField("0.00")

    /**
     * 去皮
     */
    var peel = ObservableField(false)

    /**
     * 位置
     */
    var mPosition = MutableLiveData(0)

    /**
     * 编号
     */
    var mNumber = ObservableField("")

    /**
     * 日期
     */
    var mInspectionDate = ObservableField("")

    /**
     * 记录油菜籽
     */
    var mRecordRapeseed = RecordRapeseed()



    /**
     * 适配器
     */
    var mRapeseedAdapter : RapeseedAdapter? = null



    /**
     *  Fragment集合
     */
    var mFragments = MutableLiveData<List<Fragment>>()

    /**
     * 油菜籽杂质
     */
    var mRapeseedImpurityFragment = RapeseedImpurityFragment(mRecordRapeseed)
    /**
     * 油菜籽生芽粒
     */
    var mRapeseedSporeFragment = RapeseedSporeFragment(mRecordRapeseed)

    /**
     * 油菜籽生霉粒
     */
    var mRapeseedMildewFragment = RapeseedMildewFragment(mRecordRapeseed)

    /**
     * 油菜籽热损伤粒
     */
    var mRapeseedDamageFragment = RapeseedDamageFragment(mRecordRapeseed)

    /**
     * 油菜籽未熟粒
     */
    var mRapeseedImmatureGrainFragment = RapeseedImmatureGrainFragment(mRecordRapeseed)

    init {
        OpenSerialPort.onSerialPortListener(this)
        /**
         * 每隔milliseconds毫秒后执行next操作
         */
        Observable.interval(100, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(object :
            Observer<Long> {

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: Long) {
                /**
                 * 重量輸出命令
                 */
                OpenSerialPort.output()
            }

            override fun onError(e: Throwable) {
            }

            override fun onComplete() {
            }

        })
        /**
         * Fragment适配器
         */
        var mFragmentList = mutableListOf<Fragment>()
        //油菜籽杂质
        mFragmentList.add(mRapeseedImpurityFragment)
        //油菜籽生芽粒
        mFragmentList.add(mRapeseedSporeFragment)
        //油菜籽生霉粒
        mFragmentList.add(mRapeseedMildewFragment)
        //油菜籽热损伤粒
        mFragmentList.add(mRapeseedDamageFragment)
        //油菜籽未熟粒
        mFragmentList.add(mRapeseedImmatureGrainFragment)
        /**
         * Fragment集合
         */
        mFragments.postValue(mFragmentList)
        /**
         * 适配器
         */
        mRapeseedAdapter = RapeseedAdapter(this);

    }

    /**
     * 重量回调
     */
    override fun itemClicked(event: ByteArray?) {
        /**
         * 数值
         */
        val numericalValue = ConvertUtils.bytes2HexString(event)
        if (event!!.size >= 10) {
            if (numericalValue == Constants.FARMAR_500) {
                weighing.set("砝码500")
            } else if (numericalValue == Constants.FARMAR_1000) {
                weighing.set("砝码1000")
            } else if (numericalValue == Constants.FARMAR_2000) {
                weighing.set("砝码2000")
            }else if (numericalValue == Constants.FARMAR_3000) {
                weighing.set("砝码3000")
            } else if (numericalValue == Constants.CALIBRATION_500) {
                weighing.set("完成定标")
            } else if (numericalValue == Constants.OVERLOAD) {
                weighing.set("超重")
            } else if (numericalValue == Constants.SEND_GO_START) {
                InitializeUtils.getDefaultMaker()?.show("去皮成功")
                peel.set(false)
            }  else if (numericalValue == Constants.SHIELD) {
                weighing.set("校准中")
            } else {
                if(peel.get() == true){
                    /**
                     * 置零命令
                     */
                    OpenSerialPort.ZeroOrder()
                }
                var weight = DisposeUtils.balanceCorrection(event)
                //油菜籽杂质
                mRapeseedImpurityFragment.setWeighing(weight)
                //油菜籽生芽粒
                mRapeseedSporeFragment.setWeighing(weight)
                //油菜籽生霉粒
                mRapeseedMildewFragment.setWeighing(weight)
                //油菜籽热损伤粒
                mRapeseedDamageFragment.setWeighing(weight)
                //油菜籽未熟粒
                mRapeseedImmatureGrainFragment.setWeighing(weight)
                weighing.set(weight)
            }
        }
    }


    /**
     * Fragment回调
     */
    @SuppressLint("NotifyDataSetChanged")
    override fun onChooseClickCallback(mInt: Int) {
        mRapeseedAdapter?.notifyDataSetChanged()
        mPosition.postValue(mInt)
        when(mInt){
            0 ->{
                display.set(true)
                Constants.whetherInput  = true
                //油菜籽杂质
                mRapeseedImpurityFragment.updateRecordRice(mRecordRapeseed)
            }
            1 ->{
                display.set(true)
                Constants.whetherInput  = true
                //油菜籽生芽粒
                mRapeseedSporeFragment.updateRecordRice(mRecordRapeseed)
                //油菜籽生芽粒
                mRapeseedSporeFragment.refreshData()
            }
            2 ->{
                display.set(true)
                Constants.whetherInput  = true
                //油菜籽生霉粒
                mRapeseedMildewFragment.updateRecordRice(mRecordRapeseed)
                //油菜籽生霉粒
                mRapeseedMildewFragment.refreshData()
            }
            3 ->{
                display.set(false)
                Constants.whetherInput  = false
                //油菜籽热损伤粒
                mRapeseedDamageFragment.updateRecordRice(mRecordRapeseed)
            }
            4 ->{
                display.set(false)
                Constants.whetherInput  = false
                //油菜籽未熟粒
                mRapeseedImmatureGrainFragment.updateRecordRice(mRecordRapeseed)
            }
        }
    }


    /**
     * 更新数据
     */
    fun UpdatePage(productCategoryText : String){
        var mRecordRapeseed = RecordRapeseedDao.getInstance().QueryByNumber(productCategoryText)
        if(mRecordRapeseed.recordRapeseedId > 0){
            this.mRecordRapeseed = mRecordRapeseed
            //日期
            mInspectionDate.set(TimeUtils.millis2String(mRecordRapeseed.inspectionDate))
            //油菜籽杂质
            mRapeseedImpurityFragment.updateRecordRice(mRecordRapeseed)
            //油菜籽生芽粒
            mRapeseedSporeFragment.updateRecordRice(mRecordRapeseed)
            //油菜籽生霉粒
            mRapeseedMildewFragment.updateRecordRice(mRecordRapeseed)
            //油菜籽热损伤粒
            mRapeseedDamageFragment.updateRecordRice(mRecordRapeseed)
            //油菜籽未熟粒
            mRapeseedImmatureGrainFragment.updateRecordRice(mRecordRapeseed)
        }else{
            //唯一识别码
            mRecordRapeseed.uniqueId = productCategoryText
            //日期
            mInspectionDate.set(TimeUtils.millis2String(TimeUtils.getNowMills()))
        }
        //编号
        mNumber.set(productCategoryText)

    }

    /**
     * 释放更新页面
     */
    fun releaseRecordRice(){
        mRecordRapeseed = RecordRapeseed()
        //油菜籽杂质
        mRapeseedImpurityFragment.releaseRecordRice()
        //油菜籽生芽粒
        mRapeseedSporeFragment.releaseRecordRice()
        //油菜籽生霉粒
        mRapeseedMildewFragment.releaseRecordRice()
        //油菜籽热损伤粒
        mRapeseedDamageFragment.releaseRecordRice()
        //油菜籽未熟粒
        mRapeseedImmatureGrainFragment.releaseRecordRice()
        //编号
        mNumber.set("")
        //日期
        mInspectionDate.set("")
    }

    /**
     * 保存
     */
    fun save(){
        var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
            override fun onChooseClickCallback(mInt: Int) {
                if(mInt == 0){
                    //唯一识别码
                    mRecordRapeseed.uniqueId = mNumber.get()
                    //判断
                    if(mRecordRapeseed.recordRapeseedId > 0){
                        //设备码
                        mRecordRapeseed.deviceId = SPUtils.getInstance().getString("DeviceCode")
                        mRecordRapeseed.update()
                    }else{
                        //设备码
                        mRecordRapeseed.deviceId = SPUtils.getInstance().getString("DeviceCode")
                        if(mRecordRapeseed.save()){
                            /**
                             * 上传
                             */
                            val NetworkSettings = SPUtils.getInstance().getString("NetworkSettings")
                            if(TextUtils.isEmpty(NetworkSettings)){
                                //外网上传油菜籽天平数据
                                RapeseedUploadUtils.uploadSoybeanBalanceInfo(mRecordRapeseed,null)
                            }else{
                                //内网上传油菜籽天平数据
                                RapeseedUploadUtils.IntranetRapeseedBalanceInfo(mRecordRapeseed,null)
                            }
                        }
                    }
                    //释放更新页面
                    releaseRecordRice()
                    /**
                     * 数量加一
                     */
                    SPUtils.getInstance().put("number", SPUtils.getInstance().getInt("number") + 1)
                }
            }
        },"确认要进行上传并保存吗\n确认之后会进行新一轮的计算")
        XPopup.Builder(ActivityUtils.getTopActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .autoOpenSoftInput(false)
            .asCustom(mConfirmPopup)
            .show()
    }



    /**
     * 更新页面
     */
    fun updatePage(mRecordRapeseed : RecordRapeseed){
        this.mRecordRapeseed = mRecordRapeseed
        //编号
        mNumber.set(mRecordRapeseed.uniqueId)
        //日期
        mInspectionDate.set(TimeUtils.millis2String(mRecordRapeseed.inspectionDate))
        //油菜籽杂质
        mRapeseedImpurityFragment.updateRecordRice(mRecordRapeseed)
        //油菜籽生芽粒
        mRapeseedSporeFragment.updateRecordRice(mRecordRapeseed)
        //油菜籽生霉粒
        mRapeseedMildewFragment.updateRecordRice(mRecordRapeseed)
        //油菜籽热损伤粒
        mRapeseedDamageFragment.updateRecordRice(mRecordRapeseed)
        //油菜籽未熟粒
        mRapeseedImmatureGrainFragment.updateRecordRice(mRecordRapeseed)
    }



    /**
     * 打印
     */
    fun print(){
        if(InitializeUtils.isLinkPrinter()){
            var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
                override fun onChooseClickCallback(mInt: Int) {
                    if(mInt == 0){
                        RapeseedPrintUtils.SoybeanPrinting(mRecordRapeseed)
                    }
                }
            },"确认需要打印吗?")
            XPopup.Builder(ActivityUtils.getTopActivity())
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .autoOpenSoftInput(false)
                .asCustom(mConfirmPopup)
                .show()
        }else{
            InitializeUtils.getDefaultMaker()?.show("正在链接打印机")
            InitializeUtils.LinkPrinterModel(ActivityUtils.getTopActivity())
        }
    }

    /**
     * 去皮
     */
    fun peel(){
        InitializeUtils.getDefaultMaker()?.show("正在去皮请稍后")
        /**
         * 去皮
         */
        peel.set(true)
        /**
         * 置零命令
         */
        OpenSerialPort.ZeroOrder()
    }

    /**
     * 计算
     */
    fun calculation(){
        when(mPosition.value){
            0->{
                //油菜籽杂质
                mRapeseedImpurityFragment.calculation()
            }
            1->{
                //油菜籽生芽粒
                mRapeseedSporeFragment.calculation()
            }
            2->{
                //油菜籽生霉粒
                mRapeseedMildewFragment.calculation()
            }
            3->{
                //油菜籽热损伤粒
                mRapeseedDamageFragment.calculation()
            }
            4->{
                //油菜籽未熟粒
                mRapeseedImmatureGrainFragment.calculation()
            }
        }
        /**
         *  编号
         */
        if(TextUtils.isEmpty(mNumber.get())){
            var number = NumberDao.getInstance().acquireNumber()
            if(null != number){
                if(SPUtils.getInstance().getLong("NumberedDate") > 0){
                    val DAY = TimeUtils.getTimeSpan(
                        SPUtils.getInstance().getLong("NumberedDate"),
                        TimeUtils.getNowMills(),
                        TimeConstants.DAY
                    )
                    if (DAY == 0L) {
                        val numberString: String = number.name + SPUtils.getInstance().getInt("number", 1)
                        mRecordRapeseed.uniqueId = numberString
                        mNumber.set(numberString)
                    }else{
                        SPUtils.getInstance().put("number", 1)
                        SPUtils.getInstance().put("NumberedDate", TimeUtils.getNowMills())
                        val numberString: String = number.name + SPUtils.getInstance().getInt("number", 1)
                        mRecordRapeseed.uniqueId = numberString
                        mNumber.set(numberString)
                    }
                }
            }
        }
        /**
         * 日期
         */
        var getNowMills = TimeUtils.getNowMills()
        mInspectionDate.set(TimeUtils.millis2String(getNowMills))
        mRecordRapeseed.inspectionDate = getNowMills
    }
    /**
     * 主菜单
     */
    fun mainMenu(){
        var mConfirmPopup = ConfirmPopup(object : ChooseClickCallback{
            override fun onChooseClickCallback(mInt: Int) {
                if(mInt == 0){
                    ActivityUtils.finishActivity(RapeseedActivity::class.java)
                }
            }
        },"返回主菜单会导致当前数据丢失")
        XPopup.Builder(ActivityUtils.getTopActivity())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .autoOpenSoftInput(false)
            .asCustom(mConfirmPopup)
            .show()
    }
}